import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'
import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '@/components/Home.vue'

const routes = [
    {
        name:'home',
        path:'/',
        meta:{
            title:'首页'
        },
        component:Home,
        redirect:'/welcome',
        children:[
            {
                name:'welcome',
                path:'/welcome',
                meta:{
                    title:'欢迎体验'
                },
                component:()=>import('@/views/welcome.vue')
            },
            {
                name:'user',
                path:'/system/user',
                meta:{
                    title:'用户管理'
                },
                component:()=>import('@/views/user.vue')
            },
            {
                name:'menu',
                path:'/system/menu',
                meta:{
                    title:'菜单管理'
                },
                component:()=>import('@/views/menu.vue')
            },
            {
                name:'role',
                path:'/system/role',
                meta:{
                    title:'角色管理'
                },
                component:()=>import('@/views/role.vue')
            },
            {
                name:'oplog',
                path:'/system/oplog',
                meta:{
                    title:'日志查询'
                },
                component:()=>import('@/views/oplog.vue')
            },
            {
                name:'book',
                path:'/book/book',
                meta:{
                    title:'日志查询'
                },
                component:()=>import('@/views/book.vue')
            },
        ]
    },
    {
        name:'login',
        path:'/login',
        meta:{
            title:'登录'
        },
        component:()=>import('@/views/login.vue')
    },
    // 找不到的页面
    {
        path: "/:pathMatch(.*)",
        redirect: "/",
        name: "Redirect",
        meta: { hide: true }
    }
]

const loadView = (view) => {
    const modules = import.meta.glob("../../views/**/**.vue")
    return modules[`../..${view}`]
}

const router = createRouter({
    history:createWebHashHistory(),
    routes
})

router.beforeEach((to, from, next) => {
    NProgress.start() //开启
    let token_key = localStorage.getItem('token_key')
    let token = ''
    if(token_key){
        token = localStorage.getItem(token_key)
    }
    // console.log('凭证',token,token_key);
    // 如果用户未登录且尝试访问非登录页面，则重定向到登录页面
    if (!token && to.path !== '/login') {
        console.log('未登录,去登录',to.path);
        next('/login');
        NProgress.done()  //关闭
    } else {
        next(); // 否则，继续路由
        NProgress.done()  //关闭
    }
});

export default router

// TODO 权限需要导航守卫